﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NLogInfo;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;

namespace Order.MicroService.Api.Middleware
{
    public class ExceptionHandlingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly INLogHelper _logHelper;

        public ExceptionHandlingMiddleware(RequestDelegate next, INLogHelper logHelper)
        {
            _next = next;
            _logHelper = logHelper;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            var code = HttpStatusCode.InternalServerError; // 500 if unexpected

            if (exception is ArgumentException)
            {
                code = HttpStatusCode.BadRequest;
            }
            else if (exception is UnauthorizedAccessException)
            {
                code = HttpStatusCode.Unauthorized;
            }
            else if (exception is NotImplementedException)
            {
                code = HttpStatusCode.NotImplemented;
            }
            else if (exception is KeyNotFoundException)
            {
                code = HttpStatusCode.NotFound;
            }
            else if (exception is TimeoutException)
            {
                code = HttpStatusCode.RequestTimeout;
            }
            else if (exception is WebException)
            {
                code = HttpStatusCode.BadGateway;
            }
            else if (exception is InvalidOperationException)
            {
                code = HttpStatusCode.BadRequest;
            }

            _logHelper.LogError(exception);
            var result = JsonConvert.SerializeObject(new { Code=code, exception.Message, Data="" });
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)code;
            return context.Response.WriteAsync(result);
        }
    }
}
